<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.orderNo"
        placeholder="订单编号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="订单状态"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option label="待支付" value="PENDING" />
        <el-option label="已支付" value="PAID" />
        <el-option label="配送中" value="DELIVERED" />
        <el-option label="已完成" value="COMPLETED" />
        <el-option label="已取消" value="CANCELLED" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading..."
      border
      fit
      highlight-current-row
    >
      <el-table-column label="订单编号" prop="orderNo" align="center" width="180" />
      <el-table-column label="客户" prop="customerName" align="center" />
      <el-table-column label="总金额" prop="totalAmount" align="center" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" prop="paymentMethod" align="center" width="100" />
      <el-table-column label="配送地址" prop="deliveryAddress" align="center" show-overflow-tooltip />
      <el-table-column label="创建时间" prop="createdTime" align="center" width="180" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">
            详情
          </el-button>
          <el-button
            v-if="scope.row.status === 'PENDING'"
            type="success"
            size="small"
            @click="handleUpdateStatus(scope.row.id, 'PAID')"
          >
            确认支付
          </el-button>
          <el-button
            v-if="scope.row.status === 'PAID'"
            type="warning"
            size="small"
            @click="handleUpdateStatus(scope.row.id, 'DELIVERED')"
          >
            开始配送
          </el-button>
          <el-button
            v-if="scope.row.status === 'DELIVERED'"
            type="success"
            size="small"
            @click="handleUpdateStatus(scope.row.id, 'COMPLETED')"
          >
            完成订单
          </el-button>
          <el-button
            v-if="scope.row.status === 'PENDING'"
            type="danger"
            size="small"
            @click="handleUpdateStatus(scope.row.id, 'CANCELLED')"
          >
            取消订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.current"
        v-model:page-size="listQuery.size"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentOrder.customerName }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="配送地址" :span="2">{{ currentOrder.deliveryAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="currentOrder.items" border style="margin-top: 20px">
        <el-table-column label="商品名称" prop="name" align="center" />
        <el-table-column label="类型" prop="type" align="center" width="100">
          <template #default="scope">
            {{ scope.row.productType === 'FLOWER' ? '鲜花' : '文创产品' }}
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="price" align="center" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" align="center" width="100" />
        <el-table-column label="小计" align="center" width="100">
          <template #default="scope">
            ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="order-total">
        总计：<span class="price">¥{{ currentOrder.totalAmount }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getOrderById, getOrderList, updateOrderStatus } from '@/api/order';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

// 列表数据
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const listQuery = reactive({
  current: 1,
  size: 10,
  orderNo: '',
  status: ''
})

// 订单详情
const detailDialogVisible = ref(false)
const currentOrder = reactive({
  orderNo: '',
  customerName: '',
  status: '',
  paymentMethod: '',
  deliveryAddress: '',
  remark: '',
  totalAmount: 0,
  items: []
})

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    PENDING: 'warning',
    PAID: 'primary',
    DELIVERED: 'info',
    COMPLETED: 'success',
    CANCELLED: 'danger'
  }
  return map[status]
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    PENDING: '待支付',
    PAID: '已支付',
    DELIVERED: '配送中',
    COMPLETED: '已完成',
    CANCELLED: '已取消'
  }
  return map[status]
}

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const { data } = await getOrderList(listQuery)
    list.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('Failed to get order list:', error)
  } finally {
    listLoading.value = false
  }
}

// 搜索
const handleFilter = () => {
  listQuery.current = 1
  getList()
}

// 分页
const handleSizeChange = (val) => {
  listQuery.size = val
  getList()
}

const handleCurrentChange = (val) => {
  listQuery.current = val
  getList()
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const { data } = await getOrderById(row.id)
    Object.assign(currentOrder, data)
    detailDialogVisible.value = true
  } catch (error) {
    console.error('Failed to get order detail:', error)
  }
}

// 更新订单状态
const handleUpdateStatus = (id, status) => {
  const statusText = getStatusText(status)
  ElMessageBox.confirm(`确认将订单状态更新为"${statusText}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateOrderStatus(id, status)
      ElMessage.success('状态更新成功')
      getList()
    } catch (error) {
      console.error('Failed to update order status:', error)
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 30px;
}

.order-total {
  margin-top: 20px;
  text-align: right;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}
</style> 